package com.wrx.redis_learning.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wrx.redis_learning.common.AjaxResult;
import com.wrx.redis_learning.entity.User;
import com.wrx.redis_learning.utils.VerifyCode;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.rmi.MarshalledObject;


@RestController
@RequestMapping("/my")
public class MyController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final ObjectMapper mapper = new ObjectMapper();

    @GetMapping("/hello")
    public AjaxResult hello(){
        return AjaxResult.success("Hello BUG");
    }

    /**
     *向 redis 中添加数据
     * @param user 要保存的对象
     * @return AjaxResult
     */
    @SneakyThrows
    @PostMapping("/redis_add")
    public AjaxResult redis_add(@RequestBody User user){
        System.out.println(user);
        String json = mapper.writeValueAsString(user);
        System.out.println(json);
        redisTemplate.opsForValue().set(user.getUser_name(), json);
        return AjaxResult.success();
    }

    /**
     * 从 redis 中取出数据
     * @param user_name 这是 key
     * @return AjaxResult
     */
    @SneakyThrows
    @GetMapping("/redis_get")
    public AjaxResult redis_get( @RequestParam("user_name") String user_name){
        String json = (String) redisTemplate.opsForValue().get(user_name);
        User user = mapper.readValue(json, User.class);
        return AjaxResult.success(user);
    }
    @GetMapping("/code")
    public AjaxResult get_code(){
        return AjaxResult.success(VerifyCode.generateCode(6));
    }
}
